using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Npgsql;

namespace DbaseInfo
{
    public class TableInfo
    {
        private String _conn_string;
        private NpgsqlConnection _conn = null;
        private String _tablename;
        // private Hashtable _field_list;
        private List<FieldInfo> _field_list = new List<FieldInfo>();

        #region Public Properties

        public String Name
        {
            get { return _tablename; }
        }

        public int FieldCount
        {
            get { return _field_list.Count; }
        }       

        public FieldInfo[] Fields
        {
            get { return _field_list.ToArray(); }
        }

        #endregion

        /// <summary>
        /// Class constructor
        /// </summary>
        public TableInfo(String table_name, String connection_string)
        {
            _tablename = table_name;
            _conn_string = connection_string;

            try
            {
                _conn = new NpgsqlConnection(connection_string);
                _conn.Open();
                _conn.Close();

                // Retrieve field list
                GetFieldList();
            }
            catch (Exception ex)
            {
                _conn = null;
                Console.WriteLine(ex.Message);
            }
        }

        #region Private Members

        /// <summary>
        /// Builds a list of fields belonging to the associated table
        /// </summary>
        private void GetFieldList()
        {
            NpgsqlCommand command;
            NpgsqlDataReader dr;

            _conn.Open();

            try
            {
                StringBuilder tmp = new StringBuilder();

                tmp.Append("select column_name, data_type from information_schema.columns where table_schema = 'public' and table_name = '");
                tmp.Append(_tablename);
                tmp.Append("' order by column_name ASC;");

                command = new NpgsqlCommand(tmp.ToString(), _conn);
                dr = command.ExecuteReader();

                // For each field ...
                while (dr.Read())
                {
                    _field_list.Add(new FieldInfo((string)dr[0], (string)dr[1]));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Ensure conn is ALWAYS closed
                _conn.Close();
            }

        }

        #endregion
    }
}
